import $store from '../store/index.js';
import {showToast,uploadFile} from '@/common/util.js'
const imgMaxWidth = 750;
const minSize=500*1024;
let quality=85;
let maxVideoSize=10*1024*1024;
const loadTypeName=['相册','拍照','拍视频'];
const loadTypeFn=['albumImg','cameraImg','cameraVideo'];
const showLoading=()=>{
	uni.showLoading({
		title:'上传中...',
		mask:true
	});
}
const chooseImg = (source=0) => {
	let sourceType=['camera', 'album'];
	if(source==1){
		sourceType=['camera']
	}else if(source==2){
		sourceType=['album']
	}
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1,
			sizeType: ['original'],
			sourceType,
			success(res) {
				let tempFilePath = res.tempFilePaths[0];
				let size=res.tempFiles[0].size;
				resolve({src:tempFilePath,size});
			},
			fail(err) {
				console.log(err)
				// showToast("选择图片失败，请刷新重试！");
				// reject('chooseImgFail');
			}
		});
	});
};

const getImgAttr = (src) => {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src,
			success(res) {
				resolve(res);
			},
			fail(err) {
				showToast("获得图片尺寸失败，请刷新重试！");
				reject('getImgInfoFail');
			}
		})
	})
}

const compressImg = (data,maxWidth,size) => {
	return new Promise((resolve, reject) => {
		let origWidth = data.width;
		let origHeight = data.height;
		let src = data.path;
		maxWidth=maxWidth||imgMaxWidth
		let height = maxWidth * origHeight / origWidth;
		if (size<minSize) {
			resolve(src)
		} else {
			// #ifndef H5
			uni.compressImage({
				src,
				quality,
				width: maxWidth,
				height,
				success: res => {
					resolve(res.tempFilePath);
				},
				fail: (err) => {
					showToast("压缩图片失败，请刷新重试！");
					resolve(res);
				}
			})
			// #endif
			// #ifdef H5
			let img = new Image();
			img.src = src;
			img.onload = function() {
				let that = this;
				//生成canvas
				let canvas = document.createElement('canvas');
				let ctx = canvas.getContext('2d');
				// 创建属性节点
				let anw = document.createAttribute("width");
				anw.nodeValue = maxWidth;
				let anh = document.createAttribute("height");
				anh.nodeValue = height;
				canvas.setAttributeNode(anw);
				canvas.setAttributeNode(anh);
				ctx.drawImage(that, 0, 0, origWidth, origHeight, 0, 0, maxWidth, height);
				let base64 = canvas.toDataURL('image/jpeg', quality);
				// 回调函数返回base64的值
				resolve(base64);
			}
			// #endif
		}
	});
}

const chooseAndUploadImage = (source,maxWidth =1200,_quality=85) => {
	quality=_quality;
	return new Promise((resolve, reject) => {
		chooseImg(source) //选择图片
			.then(({src,size}) => {
				showLoading();
				getImgAttr(src) //得到图片尺寸
					.then(res => {
						compressImg(res,maxWidth,size) //压缩图片
							.then(_src => {
								uploadFile(_src,'image') //上传图片
									.then(url=> {
										uni.hideLoading();
										resolve(url);
									})
									.catch(err => {
										uni.hideLoading();
										reject(err)
									})
							})
					})
					.catch(err => {
						reject(err)
					})
			})
			.catch(err => {
				reject(err)
			})
	})
};
//source 0-camera/album 1-camera 2-album
const chooseVideo = (source=0)=>{
	let sourceType=['camera', 'album'];
	if(source==1){
		sourceType=['camera']
	}else if(source==2){
		sourceType=['album']
	}
	return new Promise((resolve, reject) => {
		uni.chooseVideo({
			sourceType,
			compressed:false,
			maxDuration:30,
			success(res) {
				let {size,tempFilePath}=res;
				//size单位是b
				resolve({src:tempFilePath,size})
			},
			fail(err){
				reject(err)
			}
		});
	})
}
const getVideoInfo = (src) => {
	return new Promise((resolve, reject) => {
		uni.getVideoInfo({
			src,
			success(res) {
				resolve(res);
			},
			fail(err) {
				showToast("获得视频信息失败，请刷新重试！");
				reject('getVideoInfoFail');
			}
		})
	})
}
const compressVideo = (video,size) => {
	return new Promise((resolve, reject) => {
		//#ifdef APP||MP-WEIXIN
		if(size<maxVideoSize){
			resolve(video)
		}else{
			uni.compressVideo({
				src:video,
				quality:'high',
				success: res => {
					resolve(res.tempFilePath);
				},
				fail: (err) => {
					showToast("压缩视频失败，请刷新重试！");
					resolve(err);
				}
			})
		}
		//#endif
		//#ifndef APP||MP-WEIXIN
		resolve(video)
		//#endif
	})
}
const chooseAndUploadVideo=(source)=>{
	return new Promise((resolve, reject) => {
		chooseVideo(source).then(({src,size}) => {
			showLoading();
			compressVideo(src,size).then(_src=>{
				uploadFile(_src,'video')
					.then(url=> {
						uni.hideLoading();
						resolve(url);
					})
					.catch(err => {
						uni.hideLoading();
						reject(err)
					})
			},reject)
			
		})
	})
}
const uploadAudio=(file)=>{
	return new Promise((resolve, reject) => {
		showLoading();
		uploadFile(file,'audio')
			.then(url=> {
				uni.hideLoading();
				resolve(url);
			})
			.catch(err => {
				uni.hideLoading();
				reject(err)
			})
	})
}

module.exports = {
	loadTypeName,
	loadTypeFn,
	chooseImg,
	getImgAttr,
	compressImg,
	chooseAndUploadImage,
	chooseVideo,
	chooseAndUploadVideo,
	uploadAudio
}
